package com.music.note_android.ui.notelist

import android.os.Bundle
import android.view.*
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.music.note_android.R
import com.music.note_android.data.model.Note
import com.music.note_android.databinding.FragmentNoteListBinding
import com.music.note_android.ui.search.SearchHistoryManager
import com.music.note_android.ui.search.SearchSuggestion
import com.music.note_android.ui.search.SearchSuggestionAdapter
import com.music.note_android.ui.search.SearchSuggestionType
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
class NoteListFragment : Fragment() {
    
    private var _binding: FragmentNoteListBinding? = null
    private val binding get() = _binding!!
    
    private val args: NoteListFragmentArgs by navArgs()
    private val viewModel: NoteListViewModel by viewModels()
    private lateinit var noteAdapter: NoteListAdapter
    private lateinit var searchHistoryManager: SearchHistoryManager
    private lateinit var searchSuggestionAdapter: SearchSuggestionAdapter
    
    private var isSearchMode = false
    private var isSelectionMode = false
    
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentNoteListBinding.inflate(inflater, container, false)
        return binding.root
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        

        searchHistoryManager = SearchHistoryManager(requireContext())
        
        // 处理文件夹ID参数
        args.folderId?.let { folderId ->
            viewModel.setFolderFilter(folderId)
        }
        
        setupRecyclerView()
        setupToolbar()
        setupSearchView()
        setupBottomButtons()
        observeViewModel()
    }
    
    private fun setupRecyclerView() {
        noteAdapter = NoteListAdapter(
            lifecycleOwner = this,
            onNoteClick = { note ->
                if (isSelectionMode) {
                    viewModel.toggleNoteSelection(note.id)
                } else {
                    // 打开笔记详情
                    openNoteDetail(note)
                }
            },
            onNoteLongClick = { note ->
                if (!isSelectionMode) {
                    enterSelectionMode(note.id)
                    viewModel.toggleNoteSelection(note.id)
                }
            },
            onSelectionChanged = { noteId, isSelected ->
                if (isSelectionMode) {
                    viewModel.toggleNoteSelection(noteId)
                }
            }
        )
        
        binding.rvNotes.apply {
            adapter = noteAdapter
            layoutManager = GridLayoutManager(context, 2)
            
            // 添加滚动监听，隐藏/显示底部按钮
            addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    if (dy > 0) {
                        // 向下滚动，隐藏底部按钮
                        // 向下滚动，隐藏底部按钮
                        // 注意：由于布局文件中底部按钮没有单独的ID，这里暂时注释掉动画
                        // binding.bottomButtonsLayout.animate()
                        //     .translationY(binding.bottomButtonsLayout.height.toFloat())
                        //     .setDuration(200)
                        //     .start()
                    } else if (dy < 0) {
                        // 向上滚动，显示底部按钮
                        // binding.bottomButtonsLayout.animate()
                        //     .translationY(0f)
                        //     .setDuration(200)
                        //     .start()
                    }
                }
            })
        }
        
        // 下拉刷新
        binding.swipeRefresh.setOnRefreshListener {
            // 刷新时重新加载数据，这里可以清空搜索或重新获取数据
            viewModel.clearSearch()
            binding.swipeRefresh.isRefreshing = false
        }
    }
    
    private fun setupToolbar() {
        binding.toolbar.setOnMenuItemClickListener { menuItem ->
            when (menuItem.itemId) {
                R.id.action_search -> {
                    toggleSearchMode()
                    true
                }
                R.id.action_settings -> {
                    // 打开设置页面
                    true
                }
                else -> false
            }
        }
        
        // 选择工具栏菜单项点击事件
        binding.btnSelectAll.setOnClickListener {
            viewModel.toggleSelectAll()
        }
        
        // 删除按钮暂时注释，因为布局中可能没有这个ID
        // binding.btnDelete.setOnClickListener {
        //     showDeleteConfirmDialog()
        // }
        
        // 返回按钮
        binding.btnBackFromSearch.setOnClickListener {
            exitSearchMode()
        }
        
        binding.btnExitSelection.setOnClickListener {
            exitSelectionMode()
        }
    }
    
    private fun setupSearchView() {
        // 设置搜索建议适配器
        searchSuggestionAdapter = SearchSuggestionAdapter(
            onSuggestionClick = { query ->
                binding.etSearch.setText(query)
                searchHistoryManager.addSearchQuery(query)
            },
            onSuggestionDelete = { query ->
                searchHistoryManager.removeSearchQuery(query)
            }
        )
        
        binding.etSearch.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == android.view.inputmethod.EditorInfo.IME_ACTION_SEARCH) {
                val query = binding.etSearch.text.toString()
                if (query.isNotEmpty()) {
                    viewModel.searchNotes(query)
                    searchHistoryManager.addSearchQuery(query)
                }
                true
            } else {
                false
            }
        }
        
        binding.etSearch.addTextChangedListener(object : android.text.TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
            override fun afterTextChanged(s: android.text.Editable?) {
                val query = s?.toString() ?: ""
                viewModel.searchNotes(query)
                updateSearchSuggestions(query)
            }
        })
        
        binding.btnClearSearch.setOnClickListener {
            binding.etSearch.setText("")
        }
    }
    
    private fun setupBottomButtons() {
        binding.fabFolder.setOnClickListener {
            // 打开文件夹管理页面
        }
        
        binding.fabNewNote.setOnClickListener {
            viewModel.createNewNote()
        }
        
        binding.fabMore.setOnClickListener {
            // 显示更多操作菜单
        }
    }
    
    private fun observeViewModel() {
        // 观察笔记列表
        lifecycleScope.launch {
            viewModel.displayNotes.collect { notes ->
                noteAdapter.submitList(notes)
                updateEmptyState(notes.isEmpty())
                binding.swipeRefresh.isRefreshing = false
            }
        }
        
        // 观察搜索结果
        lifecycleScope.launch {
            viewModel.searchResults.collect { results ->
                if (isSearchMode) {
                    noteAdapter.submitList(results)
                    updateSearchEmptyState(results.isEmpty() && viewModel.searchQuery.value.isNotEmpty())
                }
            }
        }
        
        // 观察加载状态
        lifecycleScope.launch {
            viewModel.isLoading.collect { isLoading ->
                binding.progressBar.isVisible = isLoading
            }
        }
        
        // 观察选择模式
        lifecycleScope.launch {
            viewModel.isSelectionMode.collect { selectionMode ->
                updateSelectionMode(selectionMode)
            }
        }
        
        // 观察选中的笔记
        lifecycleScope.launch {
            viewModel.selectedNoteIds.collect { selectedIds ->
                noteAdapter.updateSelection(selectedIds)
                updateSelectionTitle(selectedIds.size)
            }
        }
        
        // 观察错误消息
        lifecycleScope.launch {
            viewModel.errorMessage.collect { message ->
                message?.let {
                    Toast.makeText(context, it, Toast.LENGTH_SHORT).show()
                    viewModel.clearErrorMessage()
                }
            }
        }
        
        // 观察搜索历史
        lifecycleScope.launch {
            searchHistoryManager.searchHistory.collect { history ->
                if (isSearchMode) {
                    updateSearchSuggestions(binding.etSearch.text.toString())
                }
            }
        }
    }
    
    private fun toggleSearchMode() {
        if (isSearchMode) {
            exitSearchMode()
        } else {
            enterSearchMode()
        }
    }
    
    private fun enterSearchMode() {
        isSearchMode = true
        binding.toolbar.isVisible = false
        binding.searchCard.isVisible = true
        binding.etSearch.requestFocus()
    }
    
    private fun exitSearchMode() {
        isSearchMode = false
        binding.toolbar.isVisible = true
        binding.searchCard.isVisible = false
        binding.etSearch.setText("")
        binding.etSearch.clearFocus()
        viewModel.clearSearch()
    }
    
    private fun enterSelectionMode(noteId: String) {
        isSelectionMode = true
        viewModel.enterSelectionMode(noteId)
    }
    
    private fun exitSelectionMode() {
        isSelectionMode = false
        viewModel.exitSelectionMode()
    }
    
    private fun updateSelectionMode(selectionMode: Boolean) {
        isSelectionMode = selectionMode
        binding.toolbar.isVisible = !selectionMode
        binding.selectionToolbar.isVisible = selectionMode
        noteAdapter.setSelectionMode(selectionMode)
    }
    
    private fun updateSelectionTitle(count: Int) {
        binding.tvSelectionCount.text = if (count > 0) {
            "已选择 $count 项"
        } else {
            "选择项目"
        }
    }
    
    private fun updateEmptyState(isEmpty: Boolean) {
        binding.emptyStateView.isVisible = isEmpty && !isSearchMode
        binding.rvNotes.isVisible = !isEmpty || isSearchMode
    }
    
    private fun updateSearchEmptyState(isEmpty: Boolean) {
        binding.noSearchResultView.isVisible = isEmpty && isSearchMode
    }
    
    private fun showDeleteConfirmDialog() {
        val selectedCount = viewModel.selectedNoteIds.value.size
        AlertDialog.Builder(requireContext())
            .setTitle("删除笔记")
            .setMessage("确定要删除选中的 $selectedCount 个笔记吗？此操作不可撤销。")
            .setPositiveButton("删除") { _, _ ->
                viewModel.deleteSelectedNotes()
                exitSelectionMode()
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    private fun openNoteDetail(note: Note) {
        // 打开笔记编辑页面
        val intent = com.music.note_android.ui.editor.CanvasEditorActivity.newIntent(
            requireContext(),
            note.id,
            note.title
        )
        startActivity(intent)
    }
    
    private fun updateSearchSuggestions(query: String) {
        val suggestions = mutableListOf<SearchSuggestion>()
        
        // 添加搜索历史
        val history = searchHistoryManager.searchHistory.value
        history.filter { it.contains(query, ignoreCase = true) }
            .take(5)
            .forEach { historyItem ->
                suggestions.add(SearchSuggestion(historyItem, SearchSuggestionType.HISTORY))
            }
        
        // 如果查询不为空且不在历史中，添加为搜索建议
        if (query.isNotBlank() && !history.contains(query)) {
            suggestions.add(0, SearchSuggestion(query, SearchSuggestionType.SUGGESTION))
        }
        
        searchSuggestionAdapter.submitList(suggestions)
    }
    
    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}